#include "myStdio.h"

FILE_* fopen_(const char* path_name, const char* mode)
{
    int flags = 0;
    if (strcmp(mode, "w") == 0)
        flags |= O_WRONLY | O_CREAT | O_TRUNC;
    else if (strcmp(mode, "r") == 0)
        flags |= O_RDONLY;
    else if (strcmp(mode, "a") == 0)
        flags |= O_WRONLY | O_CREAT;
    int fd;
    if (flags == O_RDONLY)
        fd = open(path_name, flags);
    else
        fd = open(path_name, flags, 0666);
    if (fd == -1)
        return NULL;
    FILE_* fp = (FILE_*)malloc(sizeof(FILE_));
    fp->flags = SYNC_LINE;
    fp->fileno = fd;
    fp->size = 0;
    memset(fp->buf, '\0', MAX_SIZE);
    return fp;
}

void fwrite_(const void* ptr, int num, FILE_* fp)
{
    memcpy(fp->buf + fp->size, ptr, num);
    fp->size += num;
    if (fp->flags & SYNC_NOW)
    {
        fflush_(fp);
    }
    else if (fp->flags & SYNC_LINE)
    {
        if (fp->buf[fp->size - 1] == '\n')
            fflush_(fp);
    }
    else if (fp->flags & SYNC_FULL)
    {
        if (fp->size == MAX_SIZE)
            fflush_(fp);
    }
}

void fflush_(FILE_* fp)
{
    write(fp->fileno, fp->buf, fp->size);
    fp->size = 0;
}

void fclose_(FILE_* fp)
{
    fflush_(fp);
    close(fp->fileno);
    free(fp);
}
